package cn.turboinfo.fuyang.api.provider.common.service.impl.order;

import cn.turboinfo.fuyang.api.domain.common.service.order.RefundOrderService;
import cn.turboinfo.fuyang.api.entity.common.enumeration.common.EntityObjectType;
import cn.turboinfo.fuyang.api.entity.common.enumeration.order.RefundStatus;
import cn.turboinfo.fuyang.api.entity.common.exception.common.DataNotExistException;
import cn.turboinfo.fuyang.api.entity.common.pojo.order.RefundOrder;
import cn.turboinfo.fuyang.api.entity.common.pojo.order.RefundOrderCreator;
import cn.turboinfo.fuyang.api.provider.common.repository.database.order.RefundOrderDAO;
import cn.turboinfo.fuyang.api.provider.common.repository.database.order.RefundOrderPO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sunshow.toolkit.core.qbean.helper.component.request.QBeanCreatorHelper;
import net.sunshow.toolkit.core.qbean.helper.service.impl.DefaultQServiceImpl;
import nxcloud.foundation.core.data.support.annotation.EnableSoftDelete;
import nxcloud.foundation.core.idgenerator.IdGeneratorFacade;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@RequiredArgsConstructor
@Service
@EnableSoftDelete
public class RefundOrderServiceImpl extends DefaultQServiceImpl<RefundOrder, Long, RefundOrderPO, RefundOrderDAO> implements RefundOrderService {
    private final IdGeneratorFacade<Long> idGeneratorFacade;

    @Override
    @Transactional
    public RefundOrder save(RefundOrderCreator creator) {
        RefundOrderPO refundOrderPO = new RefundOrderPO();
        QBeanCreatorHelper.copyCreatorField(refundOrderPO, creator);

        // 手动生成ID
        refundOrderPO.setId(idGeneratorFacade.nextId());
        return convertQBean(dao.save(refundOrderPO));
    }

    @Override
    @Transactional
    public void checkAndUpdateStatus(Long refundOrderId, RefundStatus status, RefundStatus checkStatus) {
        RefundOrderPO po = getEntityWithNullCheckForUpdate(refundOrderId);
        if (po.getStatus() != checkStatus) {
            throw new RuntimeException("退款订单状态不正确");
        }
        po.setStatus(status);
    }

    @Override
    public List<RefundOrder> findByObjectId(EntityObjectType objectType, Long objectId) {
        return convertQBeanToList(dao.findByObjectIdAndObjectType(objectId, objectType));
    }

    @Override
    @Transactional
    public void deleteById(Long id) throws DataNotExistException {
        dao.deleteById(id);
    }
}
